<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\FeiShuTalkLogic;
use app\api\logic\FeiShuMessageLogic;
use app\order\logic\OrderReportDailyLogic;


class ApiAdvLogic
{
    public function __construct()
    {

    }

    /**
    * @desc    获取tiktok广告列表
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetTiktokAdList()
    {
        $app_id        = Config('Logisticskey.tiktokad.app_id');
        $secret        = Config('Logisticskey.tiktokad.secret');
        $path      = Config('Logisticskey.tiktokad.path');
        $advertiserget      = Config('Logisticskey.tiktokad.advertiserget');
        $access_token      = Config('Logisticskey.tiktokad.access_token');
        $url = $path."".$advertiserget."/?app_id=".$app_id."&secret=".$secret;
        $return = HttpUtil::getUrlTk($url, $access_token);

        $return = json_decode($return, true);
        if(isset($return['data']['list']) && !empty($return['data']['list'])){
            foreach ($return['data']['list'] as $adv) {
                //更新广告账户
                $advaccount = table('advaccount')
                    ->where('advertiser_id', $adv['advertiser_id'])
                    ->where('platform_id',3)
                    ->find();
                $data = [
                    'platform_id' => 3,
                    'status' => 1,
                    'advertiser_id' => $adv['advertiser_id'],
                    'advertiser_name' => $adv['advertiser_name'],
                    'updatetime_automatic_last' => date('Y-m-d'),
                ];
                if(empty($advaccount)){
                    table('advaccount')->insert($data);
                } else {
                    table('advaccount')->where('id', $advaccount['id'])->update($data);
                }
            }
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @desc    roi检查
    * @date    2024/8/27
    * @author  zhangheng
    */
    public function RoiInspection()
    {
        //新增规则
        $this->AddNewRules();
        //新增规则
        // die;
        $yesterday = date('Y-m-d', time() - timezone());
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['createtime', '>=', $midnightYesterday];
        $where[]  = ['createtime', '<=', $endOfYesterday]; 

        $where[] = ['shop_id', '=', 17];
        $lists = Db::name('order_achievement')
            ->field('
                sum(total_price) as total_price
            ')
            ->where($where)
            ->select()->toarray();
        if($lists){
            foreach ($lists as &$v) {
                //广告费
                $where_campaign[] = ['a.spend', '>=', 0.001];
                $where_campaign[]  = ['a.stat_time', '>=', $midnightYesterday];
                $where_campaign[]  = ['a.stat_time', '<=', $endOfYesterday]; 
                $OrderReportDailyLogic = new OrderReportDailyLogic();
                $v['advertising'] = $OrderReportDailyLogic->advertising_campaign($where_campaign,17);
                //ROI
                if ($v['advertising'] > 0.001 && $v['total_price'] > 0.001) {
                    $v['roi'] = number_format((float)$v['total_price'] / (float)$v['advertising'], 2, '.', '');
                }else{
                    $v['roi'] = 0;
                }
                //下午18点后发送消息
                $time = date('H', time());
                if(15 <= $time && $time <= 22){
                    return json(DefaultResponse(200, true, '8点之前不发消息', ''));
                }
                if($v['roi'] >= 2){
                    // 飞书消息---个人消息
                    $FeiShuMessageLogic = new FeiShuMessageLogic();
                    $system_admin = Db::name('system_admin')->field('open_id')->where('id',1)->find();
                    $open_id = $system_admin['open_id'] ?? 0;
                    if($open_id){
                        $datamsg = [
                            'message' => $yesterday."ROI:".$v['roi']."",
                            'open_id' => $open_id,
                        ];
                        $FeiShuMessageLogic->send_message($datamsg);
                    }
                    // 飞书消息---个人消息
                    $FeiShuMessageLogic = new FeiShuMessageLogic();
                    $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
                    $open_id = $system_admin['open_id'] ?? 0;
                    if($open_id){
                        $datamsg = [
                            'message' => $yesterday."ROI:".$v['roi']."",
                            'open_id' => $open_id,
                        ];
                        $FeiShuMessageLogic->send_message($datamsg);
                    }
                }
            }
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @author  zhangheng
    */
    public function AddNewRules()
    {
        // 查看某个广告账户的ROI
        $yesterday = date('Y-m-d', time() - timezone());
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');

        $RoiSendAMessage = Config('Logisticskey.RoiSendAMessage');
        if(!empty($RoiSendAMessage)){
            foreach ($RoiSendAMessage as $k=>$v) {
                $advertising = Db::name('advertising')
                    ->where('stat_time',$midnightYesterday)
                    ->where('advertiser_id',$v['advertiser_id'])
                    ->find();
                $roi = $advertising['roas'] ?? 0;
                if(empty($roi)){
                    $roi = 0;
                }
                //下午18点后发送消息
                $time = date('H', time() - timezone());
                if(0 <= $time && $time <= 8){
                    return true;
                    // return json(DefaultResponse(200, true, '美国时间0点到早上8点之前不发消息', ''));
                }
                if($roi < 1.35){
                    // 飞书消息---个人消息
                    $FeiShuMessageLogic = new FeiShuMessageLogic();
                    $system_admin = Db::name('system_admin')->field('open_id')->where('id',$v['admin_id'])->find();
                    $open_id = $system_admin['open_id'] ?? 0;
                    if($open_id){
                        $msg = '';
                        $dates = date('Y-m-d H:i', time() - timezone());
                        // $msg = $msg. "【ROI异常通知】" . PHP_EOL;
                        $msg = $msg. "美国时间【".$dates."】" . PHP_EOL;
                        $msg = $msg. "广告账户【".$v['info']."】的ROI为".$roi."";
                        $datamsg = [
                            'message' => $msg,
                            'open_id' => $open_id,
                        ];
                        $FeiShuMessageLogic->send_message($datamsg);
                    }
                    // 飞书消息---个人消息
                    $FeiShuMessageLogic = new FeiShuMessageLogic();
                    $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
                    $open_id = $system_admin['open_id'] ?? 0;
                    if($open_id){
                        $msg = '';
                        $dates = date('Y-m-d H:i', time() - timezone());
                        // $msg = $msg. "【ROI异常通知】" . PHP_EOL;
                        $msg = $msg. "美国时间【".$dates."】" . PHP_EOL;
                        $msg = $msg. "广告账户【".$v['info']."】的ROI为".$roi."";
                        $datamsg = [
                            'message' => $msg,
                            'open_id' => $open_id,
                        ];
                        $FeiShuMessageLogic->send_message($datamsg);
                    }
                };
            }
        }
        return true;
    }
    

    /**
    * @desc    广告转点更新时间
    * @date    2024/8/27
    * @author  zhangheng
    */
    public function AdUpdateTime()
    {
        // $BeijingTime = date('Y-m-d', time());
        // halt($BeijingTime);
        $UsTime = date('Y-m-d', time() - timezone());
        // if($BeijingTime == $UsTime){
            Db::name('advaccount')->where('id',"<>","")->update(
                [
                    'updatetime_automatic'  => $UsTime,
                ]
            );
        // }
        // 飞书消息---个人消息
        $FeiShuMessageLogic = new FeiShuMessageLogic();
        $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
        $open_id = $system_admin['open_id'] ?? 0;
        if($open_id){
            $datamsg = [
                'message' => $UsTime."已转点成功",
                'open_id' => $open_id,
            ];
            $FeiShuMessageLogic->send_message($datamsg);
        }

        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @desc    获取tiktok广告--历史数据
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetTiktokAdInfo($params)
    {
        //type 1拉取历史记录 2每天实时更新
        $type = $params['type']??2;
        $advertiser_id = $params['advertiser_id']??"";
        $where2 = [];
        if(!empty($advertiser_id)){
            $where2['advertiser_id'] = $advertiser_id;
        }
            switch ($type) {
                case '1':
                    $advaccount = table('advaccount')
                        ->where('platform_id',3)
                        ->where('status',1)
                        ->where($where2)
                        ->where('updatetime_automatic_last','>=','2024-05-01')
                        ->order('integrated_time asc')
                        ->find();
                    // 以广告账户维度
                    if(!empty($advaccount)){
                        $this->integrated_get($advaccount);
                    }
                    break;
                case '2':
                    $advaccount = table('advaccount')
                        ->where('platform_id',3)
                        ->where('status',1)
                        ->where($where2)
                        // ->where('updatetime_automatic','<=',date('Y-m-d', time() - timezone() - 1*600))
                        ->order('integrated_time_new asc')
                        ->find();
                    // 每天实时更新
                    if(!empty($advaccount)){
                        $this->integrated_get_new($advaccount);
                    }
                    break;
                case '3':
                    $advaccount = table('advaccount')
                        ->where('platform_id',3)
                        ->where('status',1)
                        ->where($where2)
                        // ->where('updatetime_automatic','<=',date('Y-m-d', time() - timezone() - 1*600))
                        ->order('integrated_time asc')
                        ->find();
                    // 拉取3天以内
                    if(!empty($advaccount)){
                        $this->integrated_get_last($advaccount);
                    }
                    break;
                default:
            }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @desc    获取tiktok广告--历史数据--广告系列维度
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function integrated_get($advaccount)
    {
        $path      = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token      = Config('Logisticskey.tiktokad.access_token');
        $date_start = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last']) - 1 * 24 * 3600);
        $advertiser_id = $advaccount['advertiser_id'];
        $dimensions = ['advertiser_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $url = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date_start."&end_date=".$advaccount['updatetime_automatic_last'];
        $return = HttpUtil::getUrlTk($url, $access_token);
        $return = json_decode($return, true);
        // halt($return);
        if(empty($return['data']) && !empty($return['message']) && isset($return['message'])){
            $insert = [];
            $insert['advertiser_id'] = $advertiser_id;
            $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert['type'] = 2;
            $insert['stat_time'] = strtotime($date_start);
            $insert['platform_id'] = $advaccount['platform_id'];
            $insert['error'] = $return['message'];
            Db::name('advertising')->insert($insert);
            //修改状态
            $update = [];
            $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
            //重置成当前日期
            $lastUpdateTime = strtotime($advaccount['updatetime_automatic_last']);
            $tenDaysAgo = time() - 3600*24*3;
            if((int)$lastUpdateTime <= (int)$tenDaysAgo && $advaccount['last_status'] == 1){
                $update['updatetime_automatic_last'] = date('Y-m-d', time() - timezone());
            }
            $tenDaysAgo2 = time() - 3600*24*90;
            if((int)$lastUpdateTime <= (int)$tenDaysAgo2 && $advaccount['last_status'] == 0){
                $update['last_status'] = 1;
            }

            $update['integrated_time'] = time();
            $update['status'] = 0;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            //飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "TIKTOK广告账户：".$advertiser_id."在".$date_start."发生错误:".$insert['error'];
            $FeiShuTalkLogic->send($msg);

            return true;
        }
        if(!empty($return['data']) && $return['message'] == "OK"){
                //修改状态
                $update = [];
                $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
                //重置成当前日期
                $lastUpdateTime = strtotime($advaccount['updatetime_automatic_last']);
                $tenDaysAgo = time() - 3600*24*3;
                if((int)$lastUpdateTime <= (int)$tenDaysAgo && $advaccount['last_status'] == 1){
                    $update['updatetime_automatic_last'] = date('Y-m-d', time() - timezone());
                }
                $tenDaysAgo2 = time() - 3600*24*90;
                if((int)$lastUpdateTime <= (int)$tenDaysAgo2 && $advaccount['last_status'] == 0){
                    $update['last_status'] = 1;
                }
                $update['integrated_time'] = time();
                $update['status'] = 1;
                table('advaccount')
                    ->where('id',$advaccount['id'])
                    ->update($update);
        }
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {  
                $advertisingData = [
                    'advertiser_id' => $item['dimensions']['advertiser_id'],
                    'platform_id' => $advaccount['platform_id'],
                    'stat_time_day' => $item['dimensions']['stat_time_day'],
                    'spend' => $item['metrics']['spend'],
                    'impressions' => $item['metrics']['impressions'],
                    'stat_time' => strtotime($item['dimensions']['stat_time_day']),
                    'type_name' => "API",
                    'createtime' => time(),
                ];

                htmlLog(['AdvertisingApiLog'=>$advertisingData],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                $advertising_info = Db::name('advertising')
                    ->where('advertiser_id', $advertisingData['advertiser_id'])
                    ->where('stat_time_day', $item['dimensions']['stat_time_day'])
                    // ->where('type_name', "API")
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('advertising')->where('id',$advertising_info['id'])->update($advertisingData);
                }else{
                    Db::name('advertising')->insert($advertisingData);
                }

            }
        }
        return true;
    }
    /**
    * @desc    获取tiktok广告--历史数据--广告系列维度
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function integratedCampaign_get($advaccount)
    {
        $advaccount['updatetime_automatic'] = updatetime_automatic();
        $date_start = date('Y-m-d', strtotime($advaccount['updatetime_automatic'])- 24 * 3600);
        $advertiser_id = $advaccount['advertiser_id'];
        $dimensions = ['ad_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $metrics = [
            "campaign_id",
            "campaign_name",
            "spend",
            "ad_name",
            "onsite_shopping_roas",
            "total_onsite_shopping_value",
            "real_time_conversion",
            "conversion"
        ];
        $filtering[0]["field_name"] = "ad_status";
        $filtering[0]["filter_type"] = "IN";
        $filterValue = ["STATUS_ALL"];
        $encodedFilterValue = json_encode($filterValue); 
        $filtering[0]["filter_value"] = $encodedFilterValue;
        $filtering = json_encode($filtering, true);  
        $metrics = json_encode($metrics, true);

        //请求api
        $path      = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token      = Config('Logisticskey.tiktokad.access_token');
        $url = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_AD&report_type=BASIC&dimensions=".$dimensions."&metrics=".$metrics."&filtering=".$filtering."&page_size=1000&start_date=".$date_start."&end_date=".$advaccount['updatetime_automatic'];
        $return = HttpUtil::getUrlTk($url, $access_token);
        $return = json_decode($return, true);
        $items = [];
        if(empty($return['data']) && !empty($return['message']) && isset($return['message'])){
            $insert = [];
            $insert['stat_time'] = strtotime($date_start);
            $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert['advertiser_id'] = $advertiser_id;
            $insert['platform_id'] = $advaccount['platform_id'];
            $insert['error'] = $return['message'];
            $insert['type'] = 2;
            Db::name('advertising_campaign')->insert($insert);
            //修改状态
            $update = [];
            $update['integrated_time'] = time();
            $update['status'] = 0;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            //飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "TIKTOK广告账户：".$advertiser_id."在".$date_start."发生错误:".$insert['error'];
            $FeiShuTalkLogic->send($msg);

            return true;
        }
        if(!empty($return['data']) && $return['message'] == "OK"){
                //修改状态
                $update = [];
                $update['integrated_time'] = time();
                $update['status'] = 1;
                table('advaccount')
                    ->where('id',$advaccount['id'])
                    ->update($update);
        }
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {  
                $advertisingData = [
                    'advertiser_id' => $advertiser_id,
                    'platform_id' => $advaccount['platform_id'],
                    'campaign_id' => $item['metrics']['campaign_id'],
                    'ad_id' => $item['dimensions']['ad_id'],
                    'stat_time_day' => $item['dimensions']['stat_time_day'],
                    'spend' => $item['metrics']['spend'],
                    'stat_time' => strtotime($item['dimensions']['stat_time_day']),
                    'conversion' => $item['metrics']['conversion'],
                    'onsite_shopping_roas' => $item['metrics']['onsite_shopping_roas'],
                    'campaign_name' => $item['metrics']['campaign_name'],
                    'total_onsite_shopping_value' => $item['metrics']['total_onsite_shopping_value'],
                    'real_time_conversion' => $item['metrics']['real_time_conversion'],
                    'ad_name' => $item['metrics']['ad_name']
                ];
                $items[] = $advertisingData;
            }
            if(!empty($items)){
                Db::name('advertising_campaign')
                    ->where('stat_time',">=", strtotime($date_start))
                    ->where('stat_time',"<=", strtotime($advaccount['updatetime_automatic']))
                    ->where('advertiser_id', $advertiser_id)
                    ->delete();
                Db::name('advertising_campaign')->insertAll($items);   
            }
        }
        return true;
    }

    
    /**
    * @desc    获取tiktok广告--历史数据--广告系列维度
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function integrated_get_new($advaccount)
    {
        $advaccount['updatetime_automatic'] = updatetime_automatic();
        $path      = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token      = Config('Logisticskey.tiktokad.access_token');
        $date_start = $advaccount['updatetime_automatic'];
        $end_date = date('Y-m-d', strtotime($advaccount['updatetime_automatic']) + 1 * 24 * 3600);
        $advertiser_id = $advaccount['advertiser_id'];
        $dimensions = ['advertiser_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $url = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date_start."&end_date=".$end_date;
        $return = HttpUtil::getUrlTk($url, $access_token);
        $return = json_decode($return, true);
        // halt($return);
        if(empty($return['data']) && !empty($return['message']) && isset($return['message'])){
            $insert = [];
            $insert['advertiser_id'] = $advertiser_id;
            $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert['type'] = 2;
            $insert['stat_time'] = strtotime($date_start);
            $insert['platform_id'] = $advaccount['platform_id'];
            $insert['error'] = $return['message'];
            Db::name('advertising')->insert($insert);
            //修改状态
            $update = [];
            $update['integrated_time_new'] = time();
            $update['status'] = 0;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);
                
            //飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "TIKTOK广告账户：".$advertiser_id."在".$date_start."发生错误:".$insert['error'];
            $FeiShuTalkLogic->send($msg);

            return true;
        }
        if(!empty($return['data']) && $return['message'] == "OK"){
                //修改状态
                $update = [];
                $update['integrated_time_new'] = time();
                $update['status'] = 1;
                table('advaccount')
                    ->where('id',$advaccount['id'])
                    ->update($update);
        }
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {  
                $advertisingData = [
                    'advertiser_id' => $item['dimensions']['advertiser_id'],
                    'platform_id' => $advaccount['platform_id'],
                    'stat_time_day' => $item['dimensions']['stat_time_day'],
                    'spend' => $item['metrics']['spend'],
                    'impressions' => $item['metrics']['impressions'],
                    'stat_time' => strtotime($item['dimensions']['stat_time_day']),
                    'type_name' => "API",
                    'createtime' => time(),
                ];

                htmlLog(['AdvertisingApiLog'=>$advertisingData],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                $advertising_info = Db::name('advertising')
                    ->where('advertiser_id', $advertisingData['advertiser_id'])
                    ->where('stat_time_day', $item['dimensions']['stat_time_day'])
                    // ->where('type_name', "API")
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('advertising')->where('id',$advertising_info['id'])->update($advertisingData);
                }else{
                    Db::name('advertising')->insert($advertisingData);
                }

            }
        }
        return true;
    }

    /**
    * @desc    获取tiktok广告--历史数据--广告系列维度
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function integrated_get_last($advaccount)
    {
        $path      = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token      = Config('Logisticskey.tiktokad.access_token');

        $date_start = date('Y-m-d',strtotime($advaccount['updatetime_automatic']) - 3600*24);
        $end_date = $advaccount['updatetime_automatic'];

        $advertiser_id = $advaccount['advertiser_id'];
        $dimensions = ['advertiser_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $url = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date_start."&end_date=".$end_date;
        $return = HttpUtil::getUrlTk($url, $access_token);
        $return = json_decode($return, true);
        // halt($return);
        if(empty($return['data']) && !empty($return['message']) && isset($return['message'])){
            $insert = [];
            $insert['advertiser_id'] = $advertiser_id;
            $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert['type'] = 2;
            $insert['stat_time'] = strtotime($date_start);
            $insert['platform_id'] = $advaccount['platform_id'];
            $insert['error'] = $return['message'];
            Db::name('advertising')->insert($insert);
            //修改状态
            $update = [];
            $update['integrated_time'] = time();
            $update['status'] = 0;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            // 飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "TIKTOK广告账户：".$advertiser_id."在".$date_start."发生错误:".$insert['error'];
            $FeiShuTalkLogic->send($msg);

            return true;
        }
        if(!empty($return['data']) && $return['message'] == "OK"){
                //修改状态
                $update = [];
                $update['integrated_time'] = time();
                $update['status'] = 1;
                table('advaccount')
                    ->where('id',$advaccount['id'])
                    ->update($update);
        }
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {  
                $advertisingData = [
                    'advertiser_id' => $item['dimensions']['advertiser_id'],
                    'platform_id' => $advaccount['platform_id'],
                    'stat_time_day' => $item['dimensions']['stat_time_day'],
                    'spend' => $item['metrics']['spend'],
                    'impressions' => $item['metrics']['impressions'],
                    'stat_time' => strtotime($item['dimensions']['stat_time_day']),
                    'type_name' => "API",
                    'createtime' => time(),
                ];

                htmlLog(['AdvertisingApiLog'=>$advertisingData],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                $advertising_info = Db::name('advertising')
                    ->where('advertiser_id', $advertisingData['advertiser_id'])
                    ->where('stat_time_day', $item['dimensions']['stat_time_day'])
                    // ->where('type_name', "API")
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('advertising')->where('id',$advertising_info['id'])->update($advertisingData);
                }else{
                    Db::name('advertising')->insert($advertisingData);
                }

            }
        }
        return true;
    }
    /**
    * @desc    获取tiktok广告--历史数据--广告系列维度
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function integratedCampaign_get_new($advaccount)
    {
        $advaccount['updatetime_automatic'] = updatetime_automatic();
        $date_start = $advaccount['updatetime_automatic'];
        $end_date = date('Y-m-d', strtotime($advaccount['updatetime_automatic']) + 1 * 24 * 3600);
        $advertiser_id = $advaccount['advertiser_id'];
        $dimensions = ['ad_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $metrics = [
            "campaign_id",
            "campaign_name",
            "spend",
            "ad_name",
            "onsite_shopping_roas",
            "total_onsite_shopping_value",
            "real_time_conversion",
            "conversion"
        ];
        $filtering[0]["field_name"] = "ad_status";
        $filtering[0]["filter_type"] = "IN";
        $filterValue = ["STATUS_ALL"];
        $encodedFilterValue = json_encode($filterValue); 
        $filtering[0]["filter_value"] = $encodedFilterValue;
        $filtering = json_encode($filtering, true);  
        $metrics = json_encode($metrics, true);

        //请求api
        $path      = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token      = Config('Logisticskey.tiktokad.access_token');
        $url = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_AD&report_type=BASIC&dimensions=".$dimensions."&metrics=".$metrics."&filtering=".$filtering."&page_size=1000&start_date=".$date_start."&end_date=".$end_date;
        $return = HttpUtil::getUrlTk($url, $access_token);
        $return = json_decode($return, true);
        $items = [];
        if(empty($return['data']) && !empty($return['message']) && isset($return['message'])){
            $insert = [];
            $insert['stat_time'] = strtotime($date_start);
            $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert['advertiser_id'] = $advertiser_id;
            $insert['platform_id'] = $advaccount['platform_id'];
            $insert['error'] = $return['message'];
            $insert['type'] = 2;
            Db::name('advertising_campaign')->insert($insert);
            //修改状态
            $update = [];
            $update['integrated_time'] = time();
            $update['status'] = 0;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            // 飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "TIKTOK广告账户：".$advertiser_id."在".$date_start."发生错误:".$insert['error'];
            $FeiShuTalkLogic->send($msg);
            
            return true;
        }
        if(!empty($return['data']) && $return['message'] == "OK"){
                //修改状态
                $update = [];
                $update['integrated_time'] = time();
                $update['status'] = 1;
                table('advaccount')
                    ->where('id',$advaccount['id'])
                    ->update($update);
        }
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {  
                $advertisingData = [
                    'advertiser_id' => $advertiser_id,
                    'platform_id' => $advaccount['platform_id'],
                    'campaign_id' => $item['metrics']['campaign_id'],
                    'ad_id' => $item['dimensions']['ad_id'],
                    'stat_time_day' => $item['dimensions']['stat_time_day'],
                    'spend' => $item['metrics']['spend'],
                    'stat_time' => strtotime($item['dimensions']['stat_time_day']),
                    'conversion' => $item['metrics']['conversion'],
                    'onsite_shopping_roas' => $item['metrics']['onsite_shopping_roas'],
                    'campaign_name' => $item['metrics']['campaign_name'],
                    'total_onsite_shopping_value' => $item['metrics']['total_onsite_shopping_value'],
                    'real_time_conversion' => $item['metrics']['real_time_conversion'],
                    'ad_name' => $item['metrics']['ad_name']
                ];
                $items[] = $advertisingData;
            }
            if(!empty($items)){
                Db::name('advertising_campaign')
                    ->where('stat_time',">=", strtotime($date_start))
                    ->where('stat_time',"<=", strtotime($end_date))
                    ->where('advertiser_id', $advertiser_id)
                    ->delete();
                Db::name('advertising_campaign')->insertAll($items);   
            }
        }
        return true;
    }

    /**
    * @desc    GetFacebookAdStatus--广告账户状态申诉
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetFacebookAdStatus(){
        $advaccount = table('advaccount')
            ->field('advertiser_id,account_status')
            ->where('platform_id',1)
            ->where('status',0)
            ->select()->toarray();
        if(empty($advaccount)){
            return json(DefaultResponse(200, true, '暂无数据', ''));
        }
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);

        foreach ($advaccount as $k=>$v) {
            $url = $path.'act_'.$v['advertiser_id'].'?access_token='.$token.'&fields=account_id,name,account_status&appsecret_proof='.$appsecret_proof;
            $result = HttpUtil::getUrlFB($url);
            $result = json_decode($result,true);
            if(isset($result['account_status']) && !empty($result['account_status'])){
                $update = [];
                $update['info'] = $result['name'];
                $result = $this->switch_status($result);
                // if($result['account_status'] == "DISABLED"){
                    // 飞书消息
                    // $FeiShuTalkLogic = new FeiShuTalkLogic();
                    // $msg = "FB广告账户：".$v['advertiser_id']."(".$result['name'].")状态为:".$result['account_status'].",请处理";
                    // $FeiShuTalkLogic->send($msg);
                // }
                if($result['account_status'] !== $v['account_status']){
                    $FeiShuTalkLogic = new FeiShuTalkLogic();
                    $msg = "FB广告账户：".$v['advertiser_id']."(".$result['name'].")状态变更为:".$result['account_status'].",请及时查看";
                    $FeiShuTalkLogic->send($msg);
                    //记录广告状态
                    $update_account['account_status'] = $result['account_status'];
                    Db::name('advaccount')->where('advertiser_id',$v['advertiser_id'])->update($update_account);
                }
            }

        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @desc    GetFacebookAdStatus--广告账户状态申诉
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetFacebookName(){
        $advaccount = table('advaccount')
            ->field('advertiser_id')
            ->where('platform_id',1)
            ->where('info',"")
            ->where('status',1)
            ->select()->toarray();
        if(empty($advaccount)){
            return json(DefaultResponse(200, true, '暂无数据', ''));
        }
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);

        foreach ($advaccount as $k=>$v) {
            $url = $path.'act_'.$v['advertiser_id'].'?access_token='.$token.'&fields=account_id,name&appsecret_proof='.$appsecret_proof;
            $result = HttpUtil::getUrlFB($url);
            $result = json_decode($result,true);
            if(isset($result['name']) && !empty($result['name'])){
                $update = [];
                $update['info'] = $result['name'];
                Db::name('advaccount')->where('advertiser_id',$v['advertiser_id'])->update($update);
            }

        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }
    /**
    * @desc    获取Facebook广告--历史数据
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetFacebookAdInfo($params)
    {
        $type = $params['type']??2;
        $advertiser_id = $params['advertiser_id']??"";
        $where2 = [];
        if(!empty($advertiser_id)){
            $where2['advertiser_id'] = $advertiser_id;
        }
            switch ($type) {
                case '1':
                    $advaccount = table('advaccount')
                        ->where('platform_id',1)
                        ->where('status',1)
                        ->where($where2)
                        ->where('updatetime_automatic_last','>=','2024-05-01')
                        ->order('integrated_time asc')
                        ->find();
                    // 以广告账户维度
                    if(!empty($advaccount)){
                        $this->integrated_get_fb($advaccount);
                    }
                    break;
                case '2':
                    $advaccount = table('advaccount')
                        ->where('platform_id',1)
                        ->where('status',1)
                        ->where($where2)
                        ->order('integrated_time_new asc')
                        ->find();
                    // 每天实时更新
                    if(!empty($advaccount)){
                        $this->integrated_get_fb_new($advaccount);
                    }
                    break;
                case '3':
                    $advaccount = table('advaccount')
                        ->where('platform_id',1)
                        ->where('status',1)
                        ->where($where2)
                        // ->where('updatetime_automatic','<=',date('Y-m-d', time() - timezone() - 1*600))
                        ->order('integrated_time asc')
                        ->find();
                    // 拉取3天以内
                    if(!empty($advaccount)){
                        $this->integrated_get_fb_last($advaccount);
                    }
                    break;
                default:
            }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    public function integrated_get_fb_new($advaccount){
        $advaccount['updatetime_automatic'] = updatetime_automatic();
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        $date_start = $advaccount['updatetime_automatic'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        if(!empty($advaccount)){

            //检测广告账户状态
            $datamsg = [
                'advertiser_id' => $advaccount['advertiser_id'],
                'date_start' => $date_start,
            ];
            $this->GetFacebookAdsets($datamsg);

            $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
            
            $return = HttpUtil::getUrlFB($url);
            $return = json_decode($return,true);
            if(!empty($return['error']['message']) && isset($return['error']['message'])){
                $error1 = $return['error']['message'] ?? "";
                //密钥2
                $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
                $token = $fb_token['access_token'];
                $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
                $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
                $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
                $return = HttpUtil::getUrlFB($url);
                $return = json_decode($return,true);
                if(!empty($return['error']['message']) && isset($return['error']['message'])){

                    //log
                    $insert_log = [];
                    $update['status'] = 0;
                    $insert_log['createtime'] = time();
                    $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert_log['platform_id'] = $advaccount['platform_id'];
                    $insert_log['error'] = $return['error']['message'] ?? "";
                    $insert_log['error1'] = $error1;
                    $insert_log['return'] = json_encode($return,true);
                    Db::name('advertising_log')->insert($insert_log);

                    // 飞书消息
                    $FeiShuTalkLogic = new FeiShuTalkLogic();
                    $msg = "FB广告账户：".$advaccount['advertiser_id']."在".$date_start."发生错误:".$error1;
                    $FeiShuTalkLogic->send($msg);

                    return true;
                }
            }
            
            $update = [];
            $update['integrated_time_new'] = time();
            $update['status'] = 1;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            //log
            $insert_log = [];
            $update['status'] = 1;
            $insert_log['createtime'] = time();
            $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
            $insert_log['platform_id'] = $advaccount['platform_id'];
            Db::name('advertising_log')->insert($insert_log);
            
            if (!empty($return['data']) && isset($return['data'])) {
                foreach ($return['data'] as $ka=>$va) {
                    $insert = [];
                    $insert['stat_time'] = strtotime($date_start);
                    $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert['platform_id'] = $advaccount['platform_id'];
                    $insert['impressions'] = $va['impressions'];
                    $insert['spend'] = $va['spend'];
                    $insert['roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                    $insert['cpc'] = $va['cpc'] ?? 0;
                    $insert['cpm'] = $va['cpm'] ?? 0;
                    $insert['type_name'] = "API";
                    $insert['createtime'] = time();

                    htmlLog(['AdvertisingApiLog'=>$insert],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                    $advertising_info = Db::name('advertising')
                        ->where('advertiser_id', $insert['advertiser_id'])
                        ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
                        // ->where('type_name', "API")
                        ->find();
                    if(!empty($advertising_info)){
                        Db::name('advertising')->where('id',$advertising_info['id'])->update($insert);
                    }else{
                        Db::name('advertising')->insert($insert);
                    }
                }
            }else{
                $loginfo = [];
                $loginfo['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                $loginfo['advertiser_id'] = $advaccount['advertiser_id'];
                $loginfo['return'] = $return;
                htmlLog(['AdvertisingApiLog'=>$loginfo],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');
            }
        }
        return true;
    }
    public function integrated_get_fb_last($advaccount){
        $advaccount['updatetime_automatic'] = updatetime_automatic();
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        $date_start = date('Y-m-d',strtotime($advaccount['updatetime_automatic']) - 3600*24);
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        if(!empty($advaccount)){
            $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
            $return = HttpUtil::getUrlFB($url);
            $return = json_decode($return,true);
            if(!empty($return['error']['message']) && isset($return['error']['message'])){
                $error1 = $return['error']['message'] ?? "";
                //密钥2
                $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
                $token = $fb_token['access_token'];
                $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
                $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
                $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
                $return = HttpUtil::getUrlFB($url);
                $return = json_decode($return,true);
                if(!empty($return['error']['message']) && isset($return['error']['message'])){

                    $insert = [];
                    $insert['stat_time'] = strtotime($date_start);
                    $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert['platform_id'] = $advaccount['platform_id'];
                    $insert['error'] = $return['error']['message'] ?? "";
                    $insert['type'] = 2;
                    Db::name('advertising')->insert($insert);
                    //修改状态
                    $update = [];
                    $update['integrated_time'] = time();
                    // $update['status'] = 0;
                    table('advaccount')
                        ->where('id',$advaccount['id'])
                        ->update($update);

                    //log
                    $insert_log = [];
                    $update['status'] = 0;
                    $insert_log['createtime'] = time();
                    $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert_log['platform_id'] = $advaccount['platform_id'];
                    $insert_log['error'] = $return['error']['message'] ?? "";
                    $insert_log['error1'] = $error1;
                    $insert_log['return'] = json_encode($return,true);
                    Db::name('advertising_log')->insert($insert_log);

                    // 飞书消息
                    $FeiShuTalkLogic = new FeiShuTalkLogic();
                    $msg = "FB广告账户：".$advaccount['advertiser_id']."在".$date_start."发生错误:".$error1;
                    $FeiShuTalkLogic->send($msg);

                    return true;
                }
            }
            
            $update = [];
            $update['integrated_time'] = time();
            $update['status'] = 1;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            //log
            $insert_log = [];
            $update['status'] = 1;
            $insert_log['createtime'] = time();
            $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
            $insert_log['platform_id'] = $advaccount['platform_id'];
            Db::name('advertising_log')->insert($insert_log);

            if (!empty($return['data']) && isset($return['data'])) {
                foreach ($return['data'] as $ka=>$va) {
                    $insert = [];
                    $insert['stat_time'] = strtotime($date_start);
                    $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert['platform_id'] = $advaccount['platform_id'];
                    $insert['impressions'] = $va['impressions'];
                    $insert['spend'] = $va['spend'];
                    $insert['roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                    $insert['cpc'] = $va['cpc'] ?? 0;
                    $insert['cpm'] = $va['cpm'] ?? 0;
                    $insert['type_name'] = "API";
                    $insert['createtime'] = time();

                    htmlLog(['AdvertisingApiLog'=>$insert],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                    $advertising_info = Db::name('advertising')
                        ->where('advertiser_id', $insert['advertiser_id'])
                        ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
                        // ->where('type_name', "API")
                        ->find();
                    if(!empty($advertising_info)){
                        Db::name('advertising')->where('id',$advertising_info['id'])->update($insert);
                    }else{
                        Db::name('advertising')->insert($insert);
                    }
                }
            }
        }
        return true;
    }
    public function integrated_get_fb($advaccount){
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        $date_start = $advaccount['updatetime_automatic_last'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        if(!empty($advaccount)){
            $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
            $return = HttpUtil::getUrlFB($url);
            $return = json_decode($return,true);
            echo "时间".$date_start.PHP_EOL;
            // halt($return);
            if(!empty($return['error']['message']) && isset($return['error']['message'])){
                
                // echo '广告ID:'.$advaccount['advertiser_id'];
                // // 飞书消息---个人消息
                // $FeiShuMessageLogic = new FeiShuMessageLogic();
                // $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
                // $open_id = $system_admin['open_id'] ?? 0;
                // if($open_id){
                //     $datamsg = [
                //         'message' => '报错'.$advaccount['advertiser_id'],
                //         'open_id' => $open_id,
                //     ];
                //     $FeiShuMessageLogic->send_message($datamsg);
                // }

                    // halt($return);
                $error1 = $return['error']['message'] ?? "";
                //密钥2
                $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
                $token = $fb_token['access_token'];
                $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
                $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
                $path      = Config('Logisticskey.Facebookad_two.path');
                $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
                // halt($url);
                $return = HttpUtil::getUrlFB($url);
                $return = json_decode($return,true);
                if(!empty($return['error']['message']) && isset($return['error']['message'])){

                    echo '广告ID:'.$advaccount['advertiser_id'];
                    // 飞书消息---个人消息
                    $FeiShuMessageLogic = new FeiShuMessageLogic();
                    $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
                    $open_id = $system_admin['open_id'] ?? 0;
                    if($open_id){
                        $datamsg = [
                            'message' => '报错'.$advaccount['advertiser_id'],
                            'open_id' => $open_id,
                        ];
                        $FeiShuMessageLogic->send_message($datamsg);
                    }
                    halt($return);
                    
                    //修改状态
                    $update = [];
                    $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
                    //重置成当前日期
                    $lastUpdateTime = strtotime($advaccount['updatetime_automatic_last']);
                    $tenDaysAgo = time() - 3600*24*3;
                    if((int)$lastUpdateTime <= (int)$tenDaysAgo && $advaccount['last_status'] == 1){
                        $update['updatetime_automatic_last'] = date('Y-m-d', time() - timezone());
                    }
                    $tenDaysAgo2 = time() - 3600*24*90;
                    if((int)$lastUpdateTime <= (int)$tenDaysAgo2 && $advaccount['last_status'] == 0){
                        $update['last_status'] = 1;
                    }
                    $update['integrated_time'] = time();
                    // $update['status'] = 0;
                    table('advaccount')
                        ->where('id',$advaccount['id'])
                        ->update($update);


                    //log
                    $insert_log = [];
                    $update['status'] = 0;
                    $insert_log['createtime'] = time();
                    $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert_log['platform_id'] = $advaccount['platform_id'];
                    $insert_log['error'] = $return['error']['message'] ?? "";
                    $insert_log['error1'] = $error1;
                    $insert_log['return'] = json_encode($return,true);
                    Db::name('advertising_log')->insert($insert_log);

                    // 飞书消息
                    $FeiShuTalkLogic = new FeiShuTalkLogic();
                    $msg = "FB广告账户：".$advaccount['advertiser_id']."在".$date_start."发生错误:".$error1;
                    $FeiShuTalkLogic->send($msg);

                    return true;
                }
            }

            $update = [];
            $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
            //重置成当前日期
            $lastUpdateTime = strtotime($advaccount['updatetime_automatic_last']);
            $tenDaysAgo = time() - 3600*24*3;
            if((int)$lastUpdateTime <= (int)$tenDaysAgo && $advaccount['last_status'] == 1){
                $update['updatetime_automatic_last'] = date('Y-m-d', time() - timezone());
            }
            $tenDaysAgo2 = time() - 3600*24*90;
            if((int)$lastUpdateTime <= (int)$tenDaysAgo2 && $advaccount['last_status'] == 0){
                $update['last_status'] = 1;
            }
            $update['integrated_time'] = time();
            $update['status'] = 1;
            table('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            //log
            $insert_log = [];
            $update['status'] = 1;
            $insert_log['createtime'] = time();
            $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
            $insert_log['platform_id'] = $advaccount['platform_id'];
            Db::name('advertising_log')->insert($insert_log);

            if (!empty($return['data']) && isset($return['data'])) {
                foreach ($return['data'] as $ka=>$va) {
                    $insert = [];
                    $insert['stat_time'] = strtotime($date_start);
                    $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert['platform_id'] = $advaccount['platform_id'];
                    $insert['impressions'] = $va['impressions'];
                    $insert['spend'] = $va['spend'];
                    echo "花费".$insert['spend'];
                    $insert['roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                    $insert['cpc'] = $va['cpc'] ?? 0;
                    $insert['cpm'] = $va['cpm'] ?? 0;
                    $insert['type_name'] = "API";
                    $insert['spend'] = $va['spend'];
                    $insert['createtime'] = time();
                    
                    htmlLog(['AdvertisingApiLog'=>$insert],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                    $advertising_info = Db::name('advertising')
                        ->where('advertiser_id', $insert['advertiser_id'])
                        ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
                        // ->where('type_name', "API")
                        ->find();
                    if(!empty($advertising_info)){
                        Db::name('advertising')->where('id',$advertising_info['id'])->update($insert);
                    }else{
                        Db::name('advertising')->insert($insert);
                    }

                }
            }
        }
        return true;
    }

    /**
    * @desc    获取Facebook广告--token
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetFacebookToken()
    {
        $path      = Config('Logisticskey.Facebookad.path');
        $client_id      = Config('Logisticskey.Facebookad.client_id');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        $url = $path.'oauth/access_token?grant_type=fb_exchange_token&client_id='.$client_id.'&client_secret='.$client_secret.'&fb_exchange_token='.$token;

        $result = HttpUtil::getUrlFB($url);
        
        $results = json_decode($result,true);
        // halt($results);
        $msgs = $results['error']['message'] ?? "";
        if(strpos($msgs, 'access token: Session has expired') !== false){
            // 飞书消息---个人消息
            $FeiShuMessageLogic = new FeiShuMessageLogic();
            $system_admin = Db::name('system_admin')->field('open_id')->where('id',26)->find();
            $open_id = $system_admin['open_id'] ?? 0;
            if($open_id){
                $datamsg = [
                    'message' => "FB广告账户token过期",
                    'open_id' => $open_id,
                ];
                $FeiShuMessageLogic->send_message($datamsg);
            }
            // 飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "FB广告账户token过期";
            $FeiShuTalkLogic->send($msg);
        }
        
        $arr = array();
        $arr['result'] = $result;
        $arr['time'] = time();
        $arr['type'] = 1;
        $result = json_decode($result,true);
        if(!empty($result['access_token'])){
            $arr['access_token'] = $result['access_token'];
        }
        Db::name('fb_token')->insert($arr);

        //密钥2
        $path      = Config('Logisticskey.Facebookad_two.path');
        $path      = Config('Logisticskey.Facebookad_two.path');
        $client_id      = Config('Logisticskey.Facebookad_two.client_id');
        $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
        $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        $url = $path.'oauth/access_token?grant_type=fb_exchange_token&client_id='.$client_id.'&client_secret='.$client_secret.'&fb_exchange_token='.$token;

        $result = HttpUtil::getUrlFB($url);
        $arr = array();
        $arr['result'] = $result;
        $arr['time'] = time();
        $arr['type'] = 3;
        $result = json_decode($result,true);
        if(!empty($result['access_token'])){
            $arr['access_token'] = $result['access_token'];
        }
        Db::name('fb_token')->insert($arr);
        return success('操作成功',$result);
    }

    /**
    * @desc    获取Facebook广告系列
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetFacebookAdCampaigns($id)
    {
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        // $url = $path.''.$id.'?access_token='.$token.'&fields=adlabels,created_time,name,status,account_id&appsecret_proof='.$appsecret_proof;
        $url = $path.''.$id.'?access_token='.$token.'&appsecret_proof='.$appsecret_proof;
        $result = HttpUtil::getUrlFB($url);
        $result = json_decode($result,true);
        return $result;
    }

    /**
    * @desc    Adsets
    * @date    2024/9/23
    * @author  zhangheng
    */
    public function GetFacebookAdsets($params)
    {
        $advertiser_id = $params['advertiser_id'] ?? "";
        $date_start = $params['date_start'] ?? "";
        $time = strtotime($date_start);
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        $url = $path.'act_'.$advertiser_id.'?access_token='.$token.'&fields=name,account_status&appsecret_proof='.$appsecret_proof;
        $result = HttpUtil::getUrlFB($url);
        $result = json_decode($result,true);
        if(!empty($result['error']['message']) && isset($result['error']['message'])){
            $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
            $token = $fb_token['access_token'];
            $path      = Config('Logisticskey.Facebookad_two.path');
            $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
            $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
            $url = $path.'act_'.$advertiser_id.'?access_token='.$token.'&fields=name,account_status&appsecret_proof='.$appsecret_proof;
            $result = HttpUtil::getUrlFB($url);
            $result = json_decode($result,true);
        }
        if(!empty($result['error']['message']) && isset($result['error']['message'])){
            // 飞书消息
            $FeiShuTalkLogic = new FeiShuTalkLogic();
            $msg = "FB广告账户：".$advertiser_id."在时间:".$date_start.",请求广告状态时发生错误:".$result['error']['message'];
            // $FeiShuTalkLogic->send($msg);
        }
        //记录广告状态
        if(!empty($result['account_status'])){
            $result = $this->switch_status($result);
            //记录广告状态
            $update_account['account_status'] = $result['account_status'];
            Db::name('advaccount')->where('advertiser_id',$advertiser_id)->update($update_account);
        }
        //判断状态
        if(!empty($result['account_status']) && $result['account_status'] !== "ACTIVE"){
            //归属人
            $advaccount = Db::name('advaccount')  
                ->field('  
                    d.nickname,d.open_id,
                    COALESCE(c.admin_id, c2.admin_id) as admin_id_coalesced
                ')  
                ->alias('a')  
                ->join('qu_advaccount_admin c', '  
                    c.advertiser_id = a.advertiser_id AND  
                    c.createtime <= '.$time.' AND  
                    c.updatetime > '.$time.' AND  
                    c.status = 0', 'left')  
                ->join('qu_advaccount_admin c2', '  
                    c2.advertiser_id = a.advertiser_id AND  
                    c2.createtime <= '.$time.' AND  
                    c2.status = 1', 'left')  
                ->join('qu_system_admin d', 'd.id = COALESCE(c.admin_id, c2.admin_id)', 'left') 
                ->where('a.advertiser_id',$advertiser_id)  
                ->group('COALESCE(c.admin_id, c2.admin_id)')  
                ->find();
            $admin_name = $advaccount['nickname'] ?? "无";
            $open_id = $advaccount['open_id'] ?? "";
            if(!empty($open_id)){
                // 飞书消息---个人消息
                $FeiShuMessageLogic = new FeiShuMessageLogic();
                $msg = "FB广告账户：".$advertiser_id."(".$result['name'].")在".$date_start."状态为:".$result['account_status'].",归属人：".$admin_name.",请处理";
                $datamsg = [
                    'message' => $msg,
                    'open_id' => $open_id,
                ];
                $FeiShuMessageLogic->send_message($datamsg);
            }
            // else{
                // 飞书消息
                $FeiShuTalkLogic = new FeiShuTalkLogic();
                $msg = "FB广告账户：".$advertiser_id."(".$result['name'].")在".$date_start."状态为:".$result['account_status'].",归属人：".$admin_name.",请处理";
                $FeiShuTalkLogic->send($msg);
            // }
        }
        return json(DefaultResponse(200, true, '操作成功',$result));
    }
    /**
    * @desc    Adsets
    * @author  zhangheng
    */
    public function GetFacebookAdActivity($params)
    {
        $advertiser_id = $params['advertiser_id'] ?? "";
        $date_start = $params['date_start'] ?? "";
        $time = strtotime($date_start);
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.'act_'.$advertiser_id.'/activities?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function switch_status($result)
    {
        switch ($result['account_status']) {
            case '1':
                $result['account_status'] = 'ACTIVE';
                break;
            case '2':
                $result['account_status'] = 'DISABLED';
                break;
            case '3':
                $result['account_status'] = 'UNSETTLED';
                break;
            case '7':
                $result['account_status'] = 'PENDING_RISK_REVIEW';
                break;
            case '8':
                $result['account_status'] = 'PENDING_SETTLEMENT';
                break;
            case '9':
                $result['account_status'] = 'IN_GRACE_PERIOD';
                break;
            case '100':
                $result['account_status'] = 'PENDING_CLOSURE';
                break;
            case '101':
                $result['account_status'] = 'CLOSED';
                break;
            case '201':
                $result['account_status'] = 'ANY_ACTIVE';
                break;
            case '202':
                $result['account_status'] = 'ANY_CLOSED';
                break;
            default:
                $result['account_status'] = '未知';
        }
        return $result;
    }
    
    /**
    * @desc    每天统计广告运营消耗
    * @date    2024/8/12
    * @author  zhangheng
    */
    public function DailyStatisticsOfAdv()
    {
        $t1       = microtime(true);
        $lastday = date('Y-m-d', strtotime('-3 day') - timezone());
        $endday = date('Y-m-d', strtotime('-1 day') - timezone());
        $midnightYesterday = strtotime($lastday);
        $endOfYesterday  = strtotime($endday);
        $where[]  = ['a.stat_time', '>=', $midnightYesterday];
        $where[]  = ['a.stat_time', '<=', $endOfYesterday]; 
        $where[] = ['a.spend', '>=', 0.001];
        $where[] = ['a.type', '=', 0];

        $spendTotal = Db::name('advertising')  
            ->field('  
                sum(a.spend) as spend,  
                a.platform_id as platform,  
                DATE(FROM_UNIXTIME(a.stat_time)) as date, 
                d.nickname, 
                COALESCE(c.admin_id, c2.admin_id) as admin_id_coalesced
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')  
            ->join('qu_advaccount_admin c', '  
                c.advertiser_id = b.advertiser_id AND  
                c.createtime <= a.stat_time AND  
                c.updatetime > a.stat_time AND  
                c.status = 0', 'left')  
            ->join('qu_advaccount_admin c2', '  
                c2.advertiser_id = b.advertiser_id AND  
                c2.createtime <= a.stat_time AND  
                c2.status = 1', 'left')  
            ->join('qu_system_admin d', 'd.id = COALESCE(c.admin_id, c2.admin_id)', 'left') 
            ->where($where)  
            // ->where(function ($query) {  
            //     $query->where('COALESCE(c.admin_id, c2.admin_id) IS NOT NULL');  
            // })  
            ->group('a.platform_id, COALESCE(c.admin_id, c2.admin_id), DATE(FROM_UNIXTIME(a.stat_time))')  
            ->select()->toArray();
            
        //配置
        if(!empty($spendTotal)){
            $advertisingDatas = [];
            foreach ($spendTotal as $k=>$v) {
                //添加入库
                $advertisingData = [
                    'date' => $v['date'],
                    'time' => strtotime($v['date']),
                    'spend' => $v['spend'],
                    'platform' => $v['platform'],
                    'name' => $v['nickname'] ?? "未分配",
                    'admin_id' => $v['admin_id_coalesced'] ?? 0,
                ];
                $advertisingDatas[] = $advertisingData;
            }
            $where = [];
            $where[]  = ['time', '>=', $midnightYesterday];
            $where[]  = ['time', '<=', $endOfYesterday]; 
            Db::name('advertising_report')
                ->where($where)
                ->delete();
            Db::name('advertising_report')->insertAll($advertisingDatas);
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    public function get_fb_ads_archive(){
        $token = "EAAv7DUl64V8BO6ZAWEcK8a1r7eNYrMfgLozKBtf5dUN0rc8mX7vzXWz218gZA1nDL1JUgDeOgUBjPC3KZBtVSJdDgr56bImNLmYVdeH6Y0ZBMYdMqaAeU56CBLUGYZCWnZBD9xnhZAD87y710jJpLVe5YaH0ZCaL2jixaX2Sr7qNquuf7deYn14MDApQ";
        $client_secret      = "26cd387d70fb6cef4812afd0164992cf";
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = "https://graph.facebook.com/v20.0/ads_archive?access_token=".$token."&ad_reached_countries=US&appsecret_proof=".$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);

        
        // $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        // $path      = Config('Logisticskey.Facebookad.path');
        // $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $path      = Config('Logisticskey.Facebookad_two.path');
        $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        // $ad_reached_countries = ['US'];
//         search_terms='california'" \
// -d "ad_type=POLITICAL_AND_ISSUE_ADS" \
// -d "ad_reached_countries=['US']" \
// -d "access_token=<ACCESS_TOKEN>" \
// "https://graph.facebook.com/<API_VERSION>/ads_archive"
        $url = "https://graph.facebook.com/v20.0/ads_archive?access_token=".$token."&ad_reached_countries=US&appsecret_proof=".$appsecret_proof;

        // $url = $path.'/ads_archive?access_token='.$token.'&ad_reached_countries=US&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        if(!empty($return['error']['message']) && isset($return['error']['message'])){
            //密钥2
            $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
            $token = $fb_token['access_token'];
            $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
            $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
            $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
            $return = HttpUtil::getUrlFB($url);
            $return = json_decode($return,true);
            if(!empty($return['error']['message']) && isset($return['error']['message'])){

                $insert = [];
                $insert['stat_time'] = strtotime($date_start);
                $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                $insert['advertiser_id'] = $advaccount['advertiser_id'];
                $insert['platform_id'] = $advaccount['platform_id'];
                $insert['error'] = $return['error']['message'] ?? "";
                $insert['type'] = 2;
                Db::name('advertising')->insert($insert);
                //修改状态
                $update = [];
                $update['integrated_time_new'] = time();
                // $update['status'] = 0;
                table('advaccount')
                    ->where('id',$advaccount['id'])
                    ->update($update);

                //log
                $insert_log = [];
                $update['status'] = 0;
                $insert_log['createtime'] = time();
                $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
                $insert_log['platform_id'] = $advaccount['platform_id'];
                $insert_log['error'] = $return['error']['message'] ?? "";
                $insert_log['return'] = json_encode($return,true);
                Db::name('advertising_log')->insert($insert_log);

                // 飞书消息
                $FeiShuTalkLogic = new FeiShuTalkLogic();
                $msg = "FB广告账户：".$advaccount['advertiser_id']."在".$date_start."发生错误:".$insert_log['error'];
                $FeiShuTalkLogic->send($msg);

                return true;
            }
        }
        
        $update = [];
        $update['integrated_time_new'] = time();
        $update['status'] = 1;
        table('advaccount')
            ->where('id',$advaccount['id'])
            ->update($update);

        //log
        $insert_log = [];
        $update['status'] = 1;
        $insert_log['createtime'] = time();
        $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
        $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
        $insert_log['platform_id'] = $advaccount['platform_id'];
        Db::name('advertising_log')->insert($insert_log);

        if (!empty($return['data']) && isset($return['data'])) {
            $inserts = [];
            foreach ($return['data'] as $ka=>$va) {
                $insert = [];
                $insert['stat_time'] = strtotime($date_start);
                $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                $insert['advertiser_id'] = $advaccount['advertiser_id'];
                $insert['platform_id'] = $advaccount['platform_id'];
                $insert['impressions'] = $va['impressions'];
                $insert['spend'] = $va['spend'];
                $insert['type_name'] = "API";
                $insert['createtime'] = time();

                htmlLog(['AdvertisingApiLog'=>$insert],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

                $advertising_info = Db::name('advertising')
                    ->where('advertiser_id', $insert['advertiser_id'])
                    ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
                    // ->where('type_name', "API")
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('advertising')->where('id',$advertising_info['id'])->update($insert);
                }else{
                    Db::name('advertising')->insert($insert);
                }
                
            }
        }
        return true;
    }



    /**
     * @desc    获取tiktok广告费用调试
     * @date    2024/10/06
     * @author  zhangheng
     */
    public function integrated_get_info($advaccount)
    {
        $fb_token = Db::name('fb_token')->where('access_token',"<>","")->find();
        $token = $fb_token['access_token'];
        $date_start = $advaccount['updatetime_automatic_last'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        if(empty($advaccount))   return json(DefaultResponse(201, false, '账号数据不存在', ''));
        $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        if(!empty($return['error']['message']) && isset($return['error']['message'])){
            htmlLog(['response'=>$return],OPERATE_LOG . date('Ym') . '/integrated_get_info/' . date('Ymd') . '.txt');
        }
        return $return;
    }



    /**
     * @desc    获取tiktok广告费消费方法
     * @date    2024/10/06
     * @author  zhangheng
     */
    public function integrated_get_fb_consumer($advaccount){
        $fb_token           = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token              = $fb_token['access_token'];
        $date_start         = $advaccount['updatetime_automatic_last'];
        $path               = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof    = hash_hmac('sha256', $token,$client_secret);

        if(!empty($advaccount)){
            $url    = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
            $return = HttpUtil::getUrlFB($url);
            $return = json_decode($return,true);
            if(!empty($return['error']['message']) && isset($return['error']['message'])){
                //密钥2
                $fb_token = Db::name('fb_token')->where('type',2)->where('access_token',"<>","")->order("id desc")->find();
                $token = $fb_token['access_token'];
                $client_secret      = Config('Logisticskey.Facebookad_two.client_secret');
                $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
                $url = $path.'act_'.$advaccount['advertiser_id'].'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
                $return = HttpUtil::getUrlFB($url);
                $return = json_decode($return,true);
                if(!empty($return['error']['message']) && isset($return['error']['message'])){
                    $insert = [];
                    $insert['stat_time'] = strtotime($date_start);
                    $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert['platform_id'] = $advaccount['platform_id'];
                    $insert['error'] = $return['error']['message'] ?? "";
                    $insert['type'] = 2;
                    Db::name('advertising')->insert($insert);
                    //修改状态
                    $update = [];
                    $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
                    $update['integrated_time'] = time();
                    // $update['status'] = 0;
                    Db::name('advaccount')
                        ->where('id',$advaccount['id'])
                        ->update($update);


                    //log
                    $insert_log = [];
                    $insert_log['createtime']    = time();
                    $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert_log['platform_id']   = $advaccount['platform_id'];
                    $insert_log['error']         = $return['error']['message'] ?? "";
                    $insert_log['return']        = json_encode($return,true);
                    Db::name('advertising_log')->insert($insert_log);
                    return true;
                }
            }

            $update = [];
            $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
            $update['integrated_time'] = time();
            $update['status'] = 1;
            Db::name('advaccount')
                ->where('id',$advaccount['id'])
                ->update($update);

            //log
            self::insert_advertise_log($advaccount,$date_start);
            if (!empty($return['data']) && isset($return['data'])) {
                foreach ($return['data'] as $va) {
                    $insert = [];
                    $insert['stat_time'] = strtotime($date_start);
                    $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                    $insert['advertiser_id'] = $advaccount['advertiser_id'];
                    $insert['platform_id'] = $advaccount['platform_id'];
                    $insert['impressions'] = $va['impressions'];
                    $insert['spend'] = $va['spend'];
                    $insert['roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                    $insert['cpc'] = $va['cpc'] ?? 0;
                    $insert['cpm'] = $va['cpm'] ?? 0;
                    $insert['type_name'] = "API";
                    $insert['spend'] = $va['spend'];
                    $insert['createtime'] = time();

                    htmlLog(['AdvertisingApiLog'=>$insert],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');
                    
                    $advertising_info = Db::name('advertising')
                        ->where('advertiser_id', $insert['advertiser_id'])
                        ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
                        // ->where('type_name', "API")
                        ->find();
                    if(!empty($advertising_info)){
                        Db::name('advertising')->where('id',$advertising_info['id'])->update($insert);
                    }else{
                        Db::name('advertising')->insert($insert);
                    }

                }
            }
        }
        return true;
    }



    private function insert_advertise_log($advaccount,$date_start){
        $insert_log = [];
        $insert_log['createtime']    = time();
        $insert_log['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
        $insert_log['advertiser_id'] = $advaccount['advertiser_id'];
        $insert_log['platform_id']   = $advaccount['platform_id'];
        Db::name('advertising_log')->insert($insert_log);
    }

/**
    * @desc    CampaignInfo
    * @author  zhangheng
    */
    public function GetFacebookCampaignInfo($params)
    {
        $id = $params['id'] ?? "";
        $date_start = $params['date_start'] ?? "";
        $date_end= $params['date_end'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/insights?access_token='.$token.'&fields=spend,cpc,cpm,impressions,clicks,website_purchase_roas,conversion_values,action_values,conversions,video_play_actions,video_avg_time_watched_actions,video_continuous_2_sec_watched_actions,video_30_sec_watched_actions,video_time_watched_actions,video_p25_watched_actions,video_p50_watched_actions,video_p100_watched_actions,video_play_retention_0_to_15s_actions,video_play_retention_20_to_60s_actions,video_play_retention_graph_actions,video_play_curve_actions,website_ctr,cost_per_conversion&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_end.'"}&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }


    

/**
    * @desc    CampaignInfo
    * @author  zhangheng
    */
    public function GetFacebookReport($params)
    {
        $id = $params['id'] ?? "";
        $date_start = $params['date_start'] ?? "";
        $date_end = $params['date_end'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_end.'"}&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }


    /**
    * @desc    GetAdCreativesList
    * @author  zhangheng
    */
    public function GetAdCreativesList($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.'act_'.$id.'/adcreatives?access_token='.$token.'&fields=applink_treatment,title,link_url&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }

    
    /**
    * @desc    GetAdBusinessInfo
    * @author  zhangheng
    */
    public function GetAdBusinessInfo($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'?access_token='.$token.'&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }


    /**
    * @desc    GetAdAccounts
    * @author  zhangheng
    */
    public function GetAdAccounts($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/pending_owned_ad_accounts?access_token='.$token.'&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        echo $url;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }

    /**
    * @desc    GetAdCampaignsList
    * @desc    https://developers.facebook.com/docs/marketing-api/reference/ad-account/campaigns/
    * @author  zhangheng
    */
    public function GetAdCampaignsList($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.'act_'.$id.'/campaigns?access_token='.$token.'&fields=id,name,objective,status&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }

    /**
    * @desc    GetAdsetsList
    * @author  zhangheng
    */
    public function GetAdsetsList($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/adsets?access_token='.$token.'&fields=id,name,status&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }

    

    /**
    * @desc    GetCreativesList
    * @author  zhangheng
    */
    public function GetCreativesList($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/adcreatives?access_token='.$token.'&fields=id,name,status&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }

    /**
    * @desc    GetAdsList
    * @author  zhangheng
    */
    public function GetAdsList($params)
    {
        $id = $params['id'] ?? "";
        
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/ads?access_token='.$token.'&fields=id,name,status&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        halt($return);
        
        return json(DefaultResponse(200, true, '操作成功',$return));
    }


}
